package com.getpebble.android.framework.endpoint;

import com.getpebble.android.bluetooth.protocol.ProtocolMessage;
import com.getpebble.android.framework.protocol.EndpointId;
import com.getpebble.android.framework.protocol.inbound.PblInboundRegistryMessage;
import com.getpebble.android.framework.protocol.outbound.PblOutboundRegistryMessage;
import com.getpebble.android.framework.protocol.outbound.PblOutboundRegistryMessage.RegistryCommand;
import com.getpebble.android.framework.protocol.outbound.PblOutboundRegistryMessage.RegistryKey;
import com.getpebble.android.framework.protocol.outbound.PblOutboundRegistryMessage.RegistryType;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;

class RegistryEndpoint extends Endpoint {
    private static final String TAG = RegistryEndpoint.class.getSimpleName();
    private static final Set<EndpointId> sIds = Collections.unmodifiableSet(EnumSet.of(EndpointId.FCT_REG, EndpointId.SYS_REG));
    private final Listener mListener;
    private IEndpointMessageSender mMessageSender;

    interface Listener {
        void onReceive(PblInboundRegistryMessage pblInboundRegistryMessage);
    }

    RegistryEndpoint(IEndpointMessageSender messageSender, Listener listener) {
        if (messageSender == null) {
            throw new IllegalArgumentException("'messageSender cannot be null!");
        }
        this.mMessageSender = messageSender;
        this.mListener = listener;
    }

    Set<EndpointId> getSupportedEndpoints() {
        return sIds;
    }

    private Listener getListener() {
        return this.mListener;
    }

    private IEndpointMessageSender getMessageSender() {
        return this.mMessageSender;
    }

    public boolean sendMessage(RegistryKey key, int value, RegistryType type, RegistryCommand command) {
        return getMessageSender().sendMessage(new PblOutboundRegistryMessage(key, value, type, command));
    }

    boolean onReceive(ProtocolMessage message) {
        if (message.getEndpointId() != EndpointId.FCT_REG.getCode() && message.getEndpointId() != EndpointId.SYS_REG.getCode()) {
            return false;
        }
        PblInboundRegistryMessage inboundRegistryMessage = new PblInboundRegistryMessage(message);
        Listener listener = getListener();
        if (listener != null) {
            listener.onReceive(inboundRegistryMessage);
        }
        return true;
    }
}
